import win32api , win32con ,time
from typing import Union

class KeyboardManager:
    def __init__(self):
        self.key_mapping = {
            # 特殊键
            'backspace': 0x08, 
            'tab': 0x09,
            'clear': 0x0C,
            'enter': 0x0D,
            'shift': 0x10,
            'ctrl': 0x11,
            'alt': 0x12,
            'pause': 0x13,
            'caps_lock': 0x14,
            'esc': 0x1B,
            'spacebar': 0x20,
            'page_up': 0x21,
            'page_down': 0x22,
            'end': 0x23,
            'home': 0x24,
            'left_arrow': 0x25,
            'up_arrow': 0x26,
            'right_arrow': 0x27,
            'down_arrow': 0x28,
            'select': 0x29,
            'print': 0x2A,
            'execute': 0x2B,
            'print_screen': 0x2C,
            'insert': 0x2D,
            'delete': 0x2E,
            'help': 0x2F,

            # 数字键 (0-9)
            '0': 0x30, '1': 0x31, '2': 0x32, '3': 0x33, '4': 0x34,
            '5': 0x35, '6': 0x36, '7': 0x37, '8': 0x38, '9': 0x39,

            # 字母键 (A-Z)
            'a': 0x41, 'b': 0x42, 'c': 0x43, 'd': 0x44, 'e': 0x45,
            'f': 0x46, 'g': 0x47, 'h': 0x48, 'i': 0x49, 'j': 0x4A,
            'k': 0x4B, 'l': 0x4C, 'm': 0x4D, 'n': 0x4E, 'o': 0x4F,
            'p': 0x50, 'q': 0x51, 'r': 0x52, 's': 0x53, 't': 0x54,
            'u': 0x55, 'v': 0x56, 'w': 0x57, 'x': 0x58, 'y': 0x59,
            'z': 0x5A,

            # # Windows 键
            # 'left_win': 0x5B,
            # 'right_win': 0x5C,
            # 'apps': 0x5D,

            # 数字小键盘
            'numpad0': 0x60, 'numpad1': 0x61, 'numpad2': 0x62, 'numpad3': 0x63,
            'numpad4': 0x64, 'numpad5': 0x65, 'numpad6': 0x66, 'numpad7': 0x67,
            'numpad8': 0x68, 'numpad9': 0x69,
            'multiply': 0x6A,  # 数字键盘 *
            'add': 0x6B,      # 数字键盘 +
            'separator': 0x6C,
            'subtract': 0x6D,  # 数字键盘 -
            'decimal': 0x6E,   # 数字键盘 .
            'divide': 0x6F,    # 数字键盘 /

            # 功能键 (F1-F24)
            'f1': 0x70, 'f2': 0x71, 'f3': 0x72, 'f4': 0x73,
            'f5': 0x74, 'f6': 0x75, 'f7': 0x76, 'f8': 0x77,
            'f9': 0x78, 'f10': 0x79, 'f11': 0x7A, 'f12': 0x7B,
            'f13': 0x7C, 'f14': 0x7D, 'f15': 0x7E, 'f16': 0x7F,
            'f17': 0x80, 'f18': 0x81, 'f19': 0x82, 'f20': 0x83,
            'f21': 0x84, 'f22': 0x85, 'f23': 0x86, 'f24': 0x87,

            # # 锁定键
            # 'num_lock': 0x90,
            # 'scroll_lock': 0x91,

            # # 修饰键
            # 'left_shift': 0xA0,
            # 'right_shift': 0xA1,
            # 'left_ctrl': 0xA2,
            # 'right_ctrl': 0xA3,
            # 'left_alt': 0xA4,
            # 'right_alt': 0xA5,

            # # 浏览器相关
            # 'browser_back': 0xA6,
            # 'browser_forward': 0xA7,
            # 'browser_refresh': 0xA8,
            # 'browser_stop': 0xA9,
            # 'browser_search': 0xAA,
            # 'browser_favorites': 0xAB,
            # 'browser_home': 0xAC,

            # # 音量控制
            # 'volume_mute': 0xAD,
            # 'volume_down': 0xAE,
            # 'volume_up': 0xAF,

            # # 媒体控制
            # 'media_next_track': 0xB0,
            # 'media_prev_track': 0xB1,
            # 'media_stop': 0xB2,
            # 'media_play_pause': 0xB3,

            # # 其他特殊键
            # 'semicolon': 0xBA,      # ;
            # 'plus': 0xBB,           # +
            # 'comma': 0xBC,          # ,
            # 'minus': 0xBD,          # -
            # 'period': 0xBE,         # .
            # 'forward_slash': 0xBF,  # /
            # 'grave': 0xC0,          # `
            # 'open_bracket': 0xDB,   # [
            # 'back_slash': 0xDC,     # \
            # 'close_bracket': 0xDD,  # ]
            # 'quote': 0xDE,          # '
        }

    def send_key(self, hwnd: int, key: Union[str, int], press_time: float = 0.1) -> bool:
        """
        向指定窗口发送按键
        
        Args:
            hwnd: 窗口句柄
            key: 按键（可以是字符串或虚拟键码）
            press_time: 按键持续时间（秒）
            
        Returns:
            bool: 是否发送成功
        """
        try:
            # 获取虚拟键码
            if isinstance(key, str):
                key = key.lower()
                if key not in self.key_mapping:
                    return False
                vk_code = self.key_mapping[key]
            else:
                vk_code = key

            # 发送按键按下消息
            win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
            
            # 等待指定时间
            time.sleep(press_time)
            
            # 发送按键释放消息
            win32api.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
            
            return True
            
        except Exception as e:
            
            return False

    def send_text(self, hwnd: int, text: str, interval: float = 0.1) -> bool:
        """
        向指定窗口发送文本
        
        Args:
            hwnd: 窗口句柄
            text: 要发送的文本
            interval: 字符间的间隔时间（秒）
            
        Returns:
            bool: 是否发送成功
        """
        try:
            for char in text:
                # 获取字符的虚拟键码和扫描码
                vk_code = win32api.VkKeyScan(char)
                if vk_code == -1:
                    continue
                
                # 处理需要按住Shift键的字符
                if vk_code & 0x100:
                    win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_SHIFT, 0)
                
                # 发送字符
                win32api.PostMessage(hwnd, win32con.WM_CHAR, ord(char), 0)
                
                # 释放Shift键
                if vk_code & 0x100:
                    win32api.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_SHIFT, 0)
                
                time.sleep(interval)
            
            return True
            
        except Exception as e:
            print(f"发送文本时出错: {e}")
            return False

    def send_combination(self, hwnd: int, keys: list, press_time: float = 0.1) -> bool:
        """
        发送组合键
        
        Args:
            hwnd: 窗口句柄
            keys: 按键列表，如 ['ctrl', 'c']
            press_time: 按键持续时间（秒）
            
        Returns:
            bool: 是否发送成功
        """
        try:
            # 按下所有键
            for key in keys:
                if isinstance(key, str):
                    key = key.lower()
                    if key not in self.key_mapping:
                        return False
                    vk_code = self.key_mapping[key]
                else:
                    vk_code = key
                win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, vk_code, 0)
                time.sleep(0.05)
            
            # 等待指定时间
            time.sleep(press_time)
            
            # 释放所有键（反序）
            for key in reversed(keys):
                if isinstance(key, str):
                    vk_code = self.key_mapping[key.lower()]
                else:
                    vk_code = key
                win32api.PostMessage(hwnd, win32con.WM_KEYUP, vk_code, 0)
                time.sleep(0.05)
            
            return True
            
        except Exception as e:
            print(f"发送组合键时出错: {e}")
            return False



# 使用方法
# 创建键盘管理器实例
# kb_manager = KeyboardManager()

# list  = WindowManager().get_window()
# for window in list:
#     print(window.to_dict())

# # # 获取目标窗口句柄
# hwnd = 460332
# # # # 发送单个按键
# kb_manager.send_key(460332, 'tab')

# # # 发送文本
# # kb_manager.send_text(hwnd, "Hello World!")

# # # 发送组合键（Ctrl+C）
# kb_manager.send_combination(hwnd, ['shift', 's'])